<template>
  <view class="normal-login-container">
	<view class="logo-content align-center justify-center flex">
      <text class="welcome">Hello!</text>
    </view>
	<view class="logo-content align-center justify-center flex">
	   <text class="title">欢迎来到宠物鉴定系统</text>
	</view>

	<view class="login-form-top">
		 <view class="tabs-item tabs-active">
			 <view class="tabs-box">
				 账号登录
			 </view>
		 </view>
		 <view class="tabs-item">
			 <view class="tabs-box" >
		<!-- 		快捷登录 -->
			 </view>
		 </view>
	</view>
	<view class="login-form-content">
	  <view class="input-item flex align-center">
		<view class="iconfont icon-user icon"></view>
		<input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
	  </view>
	  <view class="input-item flex align-center">
		<view class="iconfont icon-password icon"></view>
		<input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
	  </view>
	  
	  <view class="input-item flex align-center" style="width: 60%" v-if="captchaEnabled">
	    <view class="iconfont icon-code icon"></view>
	    <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
	    <view class="login-code"> 
	      <image :src="codeUrl" @click="getCode" class="login-code-img"></image>
	    </view>
	  </view>

	  <view class="action-btn">
		<button @click="handleLogin" class="login-btn cu-btn block lg round">登陆</button>
	  </view>
	  <view class="action-btn">
		<button @click="handleUserRegister" class="register-btn cu-btn block lg round">注册</button>
	  </view>
	</view>


	<modal-dialog
	  :show="showModal"
	  :title="noticeList.noticeTitle"
	  :content="noticeList.noticeContent"
	  content-is-html
	  @confirm="loginSuccess"
	  @close="showModal = false"
	> 
	</modal-dialog>

	<!-- #ifdef MP-WEIXIN -->
		<ws-wx-privacy id="privacy-popup"></ws-wx-privacy> 
	<!-- #endif -->
	
  </view>
</template>

<script>
  import request from '@/utils/request';
  import modalDialog from '@/components/modal-dialog.vue'
  import { login, getCodeImg } from '@/api/login'
  import { getDict } from '@/api/system/dict'
  import { getNotice } from '@/api/system/notice'
  import { setToken } from '@/utils/auth'; // 假设有一个工具函数用于保存 token
  export default {
	components: { modalDialog },  
    data() {
      return {
        codeUrl: "",
		captchaEnabled: true,
	
		isChecking: false,
		loginLock: false, // 防止重复提交
		
        // 用户注册开关
        register: false,
		// 隐私协议
		isClause: true,
		token: null, // token
        globalConfig: getApp().globalData.config,
        loginForm: {
          username: "",
          smsCode: "",
        },
		Authorization : "",
		showModal: false,
		page: '1',
		pageSize:'10',
		noticeData: [],
		noticeList: [],
      }

    },
    onShow() {
	  if (this.isChecking) return;
	  this.isChecking = true;

	  (async () => {
		try {
		  // 1. 检查token是否存在
		  const token = uni.getStorageSync('token');
		  if (!token) {
			return; // 没有token直接返回
		  }

		  uni.showLoading({ title: '自动登录中...' });
		  // 3. 获取用户信息
		  const userInfo = await this.$store.dispatch('GetInfo');
		  console.log('用户信息:', userInfo); // 打印用户信息
		  
		  uni.setStorageSync('userInfo', userInfo);
		

		  // 4. 登录成功跳转
		  this.$tab.reLaunch('/pages/index');
		} catch (err) {
		  console.error('自动登录失败:', err);
		  uni.removeStorageSync('token');
		  uni.removeStorageSync('userInfo');

		} finally {
		  this.isChecking = false;
		  uni.hideLoading();
		}
	  })();
	}, 

	mounted () {
		this.getCode()
	},
    methods: {

      // 用户注册
      handleUserRegister() {
        this.$tab.navigateTo(`/pages/register`)
      },
	  // 微信登录
	  wxLogin() {
	    // this.$tab.navigateTo(`/pages/chuci`)
		this.$tab.navigateTo(`/pages/wxlogin`)
		// this.$tab.reLaunch(`/pages/index`)
	  },
	  
      // 获取图形验证码
      getCode() {
        getCodeImg().then(res => {
          this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
          if (this.captchaEnabled) {
            this.codeUrl = 'data:image/gif;base64,' + res.img
            this.loginForm.uuid = res.uuid
          }
        })
      },
      // 登录方法
      // async handleLogin() {
      //   this.$store.dispatch('Login', this.loginForm).then((res) => {
      // 		  console.log(res)
      // 		  this.Authorization = res.token
      // 		  localStorage.setItem('token', this.Authorization)
      // 		  // uni.setStorageSync('token', this.Authorization);
      // 		  setToken(this.Authorization); // 保存 token 到本地存储
      //     this.$modal.closeLoading()
      //     this.loginSuccess()
      //   }).catch(() => {
      //     if (this.captchaEnabled) {
      //       this.getCode()
      //     }
      //   })
      
      		
      // },
	  async handleLogin() {
	    try {
	      const res = await this.$store.dispatch('Login', this.loginForm);
	      console.log('登录响应:', res);
	      
	      this.Authorization = res.token;
	      // 确保token存储正确
	      uni.setStorageSync('token', this.Authorization);
	      setToken(this.Authorization);
	      
	      // 调用loginSuccess
		  
	      this.getList()

	    } catch (error) {
	      console.error('登录失败:', error);
	      this.$modal.closeLoading();
	      uni.showToast({
	        title: '登录失败: ' + (res.msg),
	        icon: 'none'
	      });
	      
	      if (this.captchaEnabled) {
	        this.getCode();
	      }
	    }
	  },
      // 登录成功后，处理函数
      loginSuccess(result) {
		this.showModal = false
        // 设置用户信息
        this.$store.dispatch('GetInfo').then(res => {
          const userInfo = res
          uni.setStorageSync('userInfo', userInfo);
          this.$tab.reLaunch('/pages/index')
        })
		

	  },
	  getList() {
	    return getNotice({ pageNum: this.page, pageSize: this.pageSize })
	  	.then((response) => {
	  	  console.log(response)
	  	  this.noticeList = response.rows[response.rows.length - 1];
	  	  console.log(this.noticeList)
	  	});
	  },
    }
  }
</script>

<style lang="scss">
  page {
	padding: 0 60rpx;
    background-color: #f6f6f6;
	box-sizing: border-box;
  }

  .normal-login-container {
	padding-top: 300rpx;
    width: 100%;
	box-sizing: border-box;


    .logo-content {
      width: 100%;

      .welcome {
		display: block;
		width: 100%;
        font-size: 80rpx;
		color: #319efc;
		font-family: 'Noto Sans SC', sans-serif;
		font-weight: bold; /* 常规体 */
      }
	  
	  .title {
		display: block;
		width: 100%;
	    font-size: 36rpx;
		color: #319efc;
		font-family: 'Noto Sans SC', sans-serif;
		font-weight: bold; /* 常规体 */
	  }
    }
	.login-form-top{
		margin-top: 96rpx;
		display: block;
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		border-radius: 40rpx 40rpx 0 0;
		background-color: #fbfbfc;
		
		.tabs-item{
			width: 50%;
			height: 100%;
			float: left;
			color: #939393;
			font-size: 36rpx;
			font-weight: bold;
			background-color: #f6f6f6;
			border-radius: 0 0 0 40rpx;
		}
		.tabs-active{
			color: #319efc;
	
			
			.tabs-box{
				position: relative;
				width: 100%;
				height: 100%;
				background-color: #fbfbfc;
				border-radius: 40rpx 40rpx 0 0;
			}
			
			.tabs-box::after {
			  content: "";
			  position: absolute;
			  left: 50%; /* 横线居中 */
			  bottom: 8px; /* 调整横线与文字的距离 */
			  width: 20%; /* 横线长度为文字的60% */
			  height: 2px; /* 横线粗细 */
			  background: #319efc; /* 横线颜色（示例为番茄红） */
			  transform: translateX(-50%); /* 水平居中 */
			}
		}
	}
    .login-form-content {
	  
	  padding: 20rpx 30rpx 50rpx 30rpx;
	  display: block;
	  text-align: center;
	  background-color: #fbfbfc;
	  border-radius: 0 40rpx 40rpx 40rpx;
	  box-sizing: border-box;


      .input-item {
		margin-top: 34rpx;
        background-color: #edeef3;
        height: 90rpx;
        border-radius: 40rpx;

        .icon {
          font-size: 38rpx;
          margin-left: 10px;
          color: #999;
        }

        .input {
          width: 100%;
          font-size: 30rpx;
          line-height: 20px;
          text-align: left;
          padding-left: 15px;
        }

      }

      .login-btn {
        margin-top: 34rpx;
        height: 90rpx;
        border-radius: 40rpx;
		color: #ffffff;
		background-color: #319efc;
      }
	  .register-btn {
	    margin-top: 34rpx;
	    height: 90rpx;
	    border-radius: 40rpx;
		color: #939393;
		background-color: transparent;
	  }
  
	  
      
      .login-code {
        height: 38px;
        float: right;
      
        .login-code-img {
          height: 38px;
          position: absolute;
          margin-left: 10px;
          width: 200rpx;
        }
      }
    }
  
	// 协议
	.protocol {
	  margin-top: 40rpx;
	  color: #939393;
	  font-size: 30rpx;
	  line-height: 30rpx;
	  
	  span{
		  margin-right: 10rpx;
		  display: block;
		  width: 30rpx;
		  height: 30rpx;
		  border: 1px solid #319efc;
		  border-radius: 50%;
		  float: left;
	  }
	  
	  image{
		  margin-right: 10rpx;
		  width: 30rpx;
		  height: 30rpx;
		  line-height: 30rpx;
		  float: left;
	  }
	  
	  text{
		  float: left;
	  }
	}
  }

</style>
